package org.xxpay.pay.channel.redpay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.MyBase64;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author: dingzhiwei
 * @date: 19/1/20
 * @description: 转银行卡通道支付接口
 */
@Service
public class RedpayPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(RedpayPaymentService.class);

    private static AtomicLong pay_seq = new AtomicLong(0L);

    @Override
    public String getChannelName() {
        return RedpayConfig.CHANNEL_NAME;
    }

    @Override
    public String getOrderId(PayOrder payOrder) {
        SimpleDateFormat fm = new SimpleDateFormat("yyMMddHHmmss");
        return String.format("P%sR%04d", fm.format(new Date()), pay_seq.getAndIncrement() % 10000);
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        AbstractRes retObj;
        switch (channelId) {
            case RedpayConfig.CHANNEL_NAME_ALIPAY_PC :
                retObj = doTfPay4Alipay(payOrder, "pc");
                break;
            case RedpayConfig.CHANNEL_NAME_ALIPAY_H5 :
                retObj = doTfPay4Alipay(payOrder, "wap");
                break;
            default: return ApiBuilder.bizError("不支持的渠道[channelId="+channelId+"]");
        }
        return retObj;
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        // 上游没有查询接口，直接返回
        return QueryRetMsg.waiting();
    }

    /**
     * 支付宝支付(跳转页面,显示二维码)
     * @param payOrder
     * @param type
     * @return
     */
    public AbstractRes doTfPay4Alipay(PayOrder payOrder, String type) {
        RedpayConfig redpayConfig = new RedpayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        // 根据子账号配置得到转卡信息，拼接支付宝转账银行卡URL
        String alipayUserId = redpayConfig.getAlipayUserId();     // 支付宝用户ID
        String alipayAccount = redpayConfig.getAlipayAccount();   // 支付宝账号
        String amt = AmountUtil.convertCent2Dollar(payOrder.getAmount()+"");
        try {

            JSONObject o = new JSONObject();
            o.put("alipayUserId", alipayUserId);
            o.put("alipayAccount", alipayAccount);
            o.put("amount", amt);
            o.put("payOrderId", payOrder.getPayOrderId());
            String param = MyBase64.encode(o.toJSONString().getBytes());
            DBApplicationConfig dbConfig = getDBApplicationConfig();
            String toUrl = dbConfig.getConfig4PayUrl() + "/%s/alipay_red_%s.htm";
            toUrl = String.format(toUrl, RedpayConfig.CHANNEL_NAME, param);
            _log.info("[{}]生成红包URL={}", getChannelName(), toUrl);
            int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
            _log.info("[{}]更新订单状态为支付中:payOrderId={},result={}", getChannelName(), payOrder.getPayOrderId(), updateCount);


            //toUrl = "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode("alipays://platformapi/startapp?saId=10000007&qrcode=" + toUrl);
            toUrl = "https://ds.alipay.com/?from=mobilecodec&scheme="+URLEncoder.encode("alipays://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=" + toUrl);

            String codeImgUrl = genCodeImgUrl(URLEncoder.encode(toUrl));
            StringBuffer payForm = new StringBuffer();
            String toPayUrl = dbConfig.getConfig4PayUrl() + "/" + RedpayConfig.CHANNEL_NAME + "/pay_" + type + ".htm";
            Boolean autoJump = redpayConfig.getAutoJump();
            payForm.append("<form style=\"display: none\" action=\""+toPayUrl+"\" method=\"post\">");
            payForm.append("<input name=\"mchOrderNo\" value=\""+payOrder.getMchOrderNo()+"\" >");
            payForm.append("<input name=\"payOrderId\" value=\""+payOrder.getPayOrderId()+"\" >");
            payForm.append("<input name=\"amount\" value=\""+payOrder.getAmount()+"\" >");
            payForm.append("<input name=\"codeImgUrl\" value=\""+codeImgUrl+"\" >");
            payForm.append("<input name=\"codeUrl\" value=\""+toUrl+"\" >");
            payForm.append("<input name=\"autoJump\" value=\""+autoJump+"\" >");
            payForm.append("<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >");
            payForm.append("</form>");
            payForm.append("<script>document.forms[0].submit();</script>");

            // 支付链接地址
            retObj.setPayOrderId(payOrder.getPayOrderId()); // 设置支付订单ID
            String payJumpUrl = toPayUrl + "?mchOrderNo=" + payOrder.getMchOrderNo() + "&payOrderId=" + payOrder.getPayOrderId() +
                    "&amount=" + payOrder.getAmount() + "&codeImgUrl=" + URLEncoder.encode(codeImgUrl) + "&codeUrl=" + URLEncoder.encode(toUrl) +
                    "&autoJump=" + autoJump;

            retObj.setJumpInfo(payForm.toString(), payJumpUrl);

            return retObj;
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("操作失败!");
        }
    }

    public static void main(String[] args) {

        String cardNo = "6230200015683472";
        cardNo = cardNo.substring(0, 6) + "****" + cardNo.substring(cardNo.length()-4);
        System.out.println(cardNo);

    }

}
